package com.zen.lon.open.remote.support;

import org.apache.commons.collections4.MapUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.util.ClassUtils;
import org.springframework.web.client.RestTemplate;

/**
 * spring ApplicationContext 上下文持有器
 *
 * @author ZonLen since on 2021/7/6 下午10:26
 */
public final class ApplicationContextProvider {

  private static ApplicationContext applicationContext;

  public static synchronized void initRemoteClientContext(ApplicationContext applicationContext) {
    ApplicationContextProvider.applicationContext = applicationContext;
  }

  /**
   * 获取容器环境
   */
  private static Environment environment() {
    return applicationContext.getEnvironment();
  }

  /**
   * 获取配置信息
   */
  public static String getProperty(String propertyKey) {
    return environment().getProperty(propertyKey);
  }

  public static String getProperty(String propertyKey, String defaultVal) {
    return environment().getProperty(propertyKey, defaultVal);
  }

  /**
   * 解析并获取配置信息
   */
  public static String resolvePlaceholders(String placeholders) {
    return environment().resolvePlaceholders(placeholders);
  }

  /**
   * 获取spring bean
   */
  public static <B> B getBean(Class<B> beanClass) {
    return applicationContext.getBean(beanClass);
  }

  public static <B> B getBeanShouldNull(Class<B> beanClass) {
    if (applicationContext.containsBean(beanClass.getName()) || applicationContext.containsBean(
        ClassUtils.getShortName(beanClass))) {
      return applicationContext.getBean(beanClass);
    }
    return null;
  }

  public static <B> B getBeanByType(Class<B> bClass) {
    return MapUtils.emptyIfNull(applicationContext.getBeansOfType(bClass)).values().stream()
        .findFirst().orElse(null);
  }


  public static <B> B getBean(String beanName, Class<B> beanClass) {
    return applicationContext.getBean(beanName, beanClass);
  }
}
